package com.example.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * yml读取工具类
 *
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/2/8 13:56
 */
public class YmlUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(YmlUtil.class);

    private static final String SPE_FLAG = ":";

    private static final String NULL = " ";
    private static String bootstrap_file = "classpath:conf/generator.yml";
    private static String application_file = "classpath:application.yml";

    private static Map<String, String> result = new HashMap<>();

    /**
     * 根据文件名获取yml的文件内容
     *
     * @param filePath
     * @param keys     第一个参数对应第一个key，第二个参数对应第二个key 比如spring.name下的所有 就是两个参数、
     *                 getYmlByFileName(bootstrap_file,"spring", "name");
     * @return
     */
    public static Map<String, String> getYmlByFileName(String filePath, String... keys) {
        result = new HashMap<>();
        if (filePath == null) filePath = bootstrap_file;
        InputStream in = null;
        try {
            File file = ResourceUtils.getFile(filePath);
            in = new BufferedInputStream(new FileInputStream(file));
            Yaml props = new Yaml();
            Object obj = props.loadAs(in, Map.class);
            Map<String, Object> param = (Map<String, Object>) obj;

            for (Map.Entry<String, Object> entry : param.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                if (keys.length != 0 && !keys[0].equals(key)) {
                    continue;
                }
                if (val instanceof Map) {
                    forEachYaml(key, (Map<String, Object>) val, 1, keys);
                } else {
                    result.put(key, val.toString());
                }
            }
            return result;
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 根据key获取值
     *
     * @param key
     * @return
     */
    public static String getValue(String key) throws FileNotFoundException {
        Map<String, String> map = getYmlByFileName(null);
        if (map == null) return null;
        return map.get(key);
    }

    public static Boolean editYmlByKey(String key, Object value) throws IOException {
        if (key.contains(".")) {
            List<String> split = StrUtil.split(key, ".");
            key = split.get(split.size() - 1);
        }
        ApplicationHome h = new ApplicationHome(YmlUtil.class);

        File file = new File(h.getDir() + "\\config\\application.yml");
        List<String> list = FileUtil.readLines(file, Charset.defaultCharset());
        ArrayList<String> list1 = new ArrayList<>();
        String finalKey = key;
        list.forEach(e -> {
            if (e.trim().contains(finalKey)) {
                List<String> list2 = StrUtil.split(e, SPE_FLAG);
                e = list2.get(0) + SPE_FLAG + NULL + value;
            }
            list1.add(e);
        });

        boolean del = FileUtil.del(application_file);
        if (del) {
            FileUtil.writeLines(list1, file.getPath(), Charset.defaultCharset()).createNewFile();
        } else return false;

        return true;
    }

    /**
     * 遍历yml文件，获取map集合
     *
     * @param key_str
     * @param obj
     * @param i
     * @param keys
     */
    public static void forEachYaml(String key_str, Map<String, Object> obj, int i, String... keys) {
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();
            if (keys.length > i && !keys[i].equals(key)) {
                continue;
            }
            String str_new = "";
            if (StrUtil.isNotEmpty(key_str)) {
                str_new = key_str + "." + key;
            } else {
                str_new = key;
            }
            if (val instanceof Map) {
                forEachYaml(str_new, (Map<String, Object>) val, ++i, keys);
                i--;
            } else {
                result.put(str_new, val.toString());
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        Map<String, String> ymlByFileName = getYmlByFileName(bootstrap_file, "gen");
        Set<Map.Entry<String, String>> entries = ymlByFileName.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() + "===" + entry.getValue());
        }
    }
}
